package EnterpriseAlgorithm.Stack_Queue.Code.CatsAndDog_Queue;

import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;

class DogCatQueue {
    private final Queue<PetEnterQueue> dogQ;
    private final Queue<PetEnterQueue> catQ;
    private long count;

    public DogCatQueue() {
        this.dogQ = new LinkedList<PetEnterQueue>();
        this.catQ = new LinkedList<PetEnterQueue>();
        this.count = 0;
    }

    public void add(Pet pet) {  // 这时候进行了向上转型
        if (pet.getPetType().equals("dog")) {
            this.dogQ.add(new PetEnterQueue(pet, this.count++));
        } else if (pet.getPetType().equals("cat")) {
            this.catQ.add(new PetEnterQueue(pet, this.count++));
        } else {
            throw new RuntimeException("err, not dog or cat");
        }
    }

    public Pet pollAll() {
        // 猫狗队列都不为空时
        if (!this.dogQ.isEmpty() && !this.catQ.isEmpty()) {
            if (this.dogQ.peek().getCount() < this.catQ.peek().getCount()) {
                return Objects.requireNonNull(this.dogQ.poll()).getPet();
            } else {
                return Objects.requireNonNull(this.catQ.poll()).getPet();
            }
        } else if (!this.dogQ.isEmpty()) {  // 猫队列为空时
            return this.dogQ.poll().getPet();
        } else if (!this.catQ.isEmpty()) {  // 狗队列为空时
            return this.catQ.poll().getPet();
        } else {  // 猫狗队列都为空时
            throw new RuntimeException("err, queue is empty!");
        }
    }
    // poll Dog()方法
    public Dog pollDog() {
        if (!this.isDogQueueEmpty()) {
            //requireNonNull(T obj)  检查指定的对象引用不是 null 。
            //Objects.requireNonNull(this.dogQ.poll()) 得到的只是Pet对象
            return (Dog) Objects.requireNonNull(this.dogQ.poll()).getPet();  // 向下转型
        } else {
            throw new RuntimeException("Dog queue is empty!");
        }
    }

    private boolean isDogQueueEmpty() {
        return this.dogQ.isEmpty();
    }

    // poll Cat()方法
    public Cat pollCat() {
        if (!this.isCatQueueEmpty()) {
            return (Cat) Objects.requireNonNull(this.catQ.poll()).getPet();
        } else {
            throw new RuntimeException("Cat queue is empty!");
        }
    }

    private boolean isCatQueueEmpty() {
        return this.catQ.isEmpty();
    }
    //判断是否为空
    public boolean isEmpty() {
        return this.dogQ.isEmpty() && this.catQ.isEmpty(); //当猫和狗队列都为空时，DogCatQueue 为空
    }
}